import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:sp_util/sp_util.dart';
import 'package:talk/pages/my/provider/theme_provider.dart';
import 'package:talk/res/constant.dart';
import 'package:talk/routers/not_found_page.dart';
import 'package:talk/routers/routers.dart';
import 'package:talk/routers/routers2.dart';
import 'package:talk/utils/NotificationService.dart';
import 'package:talk/utils/handle_error_utils.dart';
import 'package:talk/utils/log_utils.dart';

import 'home/LocaleProvider.dart';
import 'iconFont.dart';
import 'res/listData.dart';
import 'pages/tabs.dart';

Future<void> main() async {
  // 仅在Release环境不打印debug信息
  if (Constant.inProduction) {
    debugPrint = (String? message, {int? wrapWidth}) {};
  }

  WidgetsFlutterBinding.ensureInitialized();
  // 初始化通知
  await NotificationHelper().initialize();



  // 异常处理
  handleError(() async {
    // 确保Flutter框架初始化完成
    WidgetsFlutterBinding.ensureInitialized();

    // 初始化本地存储
    await SpUtil.getInstance();

    // 启动应用
    runApp(const MyApp());
  });

  // 启动时隐藏状态栏和导航栏
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
}

final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static GlobalKey<NavigatorState> navigatorKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    // 初始化日志、网络请求和路由
    initApp();
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);

    // 关键修复：确保MultiProvider在应用的最顶层
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => ThemeProvider(),
        ),
        // 确保LocaleProvider正确注册
        ChangeNotifierProvider(
          create: (_) => LocaleProvider.instance,
        )
      ],
      child: Consumer2<ThemeProvider, LocaleProvider>(
        builder: (_, ThemeProvider themeProvider, LocaleProvider localeProvider, __) {
          return OKToast(
            backgroundColor: Colors.black54,
            textPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
            radius: 20.0,
            position: ToastPosition.bottom,
            child: MaterialApp(
              debugShowCheckedModeBanner: false,
              title: 'Flutter Demo',
              theme: ThemeData(
                  pageTransitionsTheme: PageTransitionsTheme(
                    builders: Map.fromIterable(
                      TargetPlatform.values,
                      value: (_) => CustomPageTransitionBuilder3(),
                    ),
                  ),
                  scaffoldBackgroundColor: Colors.white.withOpacity(0.1),
                  primarySwatch: Colors.yellow,
                  appBarTheme: const AppBarTheme(
                    backgroundColor: Colors.white,
                    centerTitle: true,
                  )
              ),
              initialRoute: "/",
              onGenerateRoute: onGenerateRoute,
              navigatorKey: navigatorKey,
              builder: (BuildContext context, Widget? child) {
                // 确保文字大小不受系统设置影响
                final mediaQueryData = MediaQuery.of(context);
                final textScaledData = mediaQueryData.copyWith(textScaler: TextScaler.noScaling);

                return MediaQuery(
                  data: textScaledData,
                  child: BackgroundWrapper(
                    child: child!,
                  ),
                );
              },
              // 未知路由处理
              onUnknownRoute: (_) {
                return MaterialPageRoute<void>(
                  builder: (BuildContext context) => const NotFoundPage(),
                );
              },
            ),
          );
        },
      ),
    );
  }

  // 初始化应用配置
  void initApp() {
    Log.init();
    Routes.initRoutes();
  }
}

// 优化后的背景包装器组件
class BackgroundWrapper extends StatelessWidget {
  final Widget child;
  // 定义图片提供器（使用常量提升性能）
  final ImageProvider backgroundImage = const AssetImage('images/images/mask_backcolor6.png');

  const BackgroundWrapper({
    Key? key,
    required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final screenWidth = MediaQuery.of(context).size.width;
    final screenHeight = MediaQuery.of(context).size.height;


    return Stack(
      fit: StackFit.expand,
      children: [
        RepaintBoundary(
          child: Image(
            image: backgroundImage,
            fit: BoxFit.cover,
            width: screenWidth,
            height: screenHeight,
            colorBlendMode: BlendMode.modulate,
            loadingBuilder: (context, child, loadingProgress) {
              if (loadingProgress == null) return child;
              return Container(color: Colors.grey[200]);
            },
            errorBuilder: (context, error, stackTrace) {
              return Container(color: Colors.white);
            },
          ),
        ),
        child,
      ],
    );
  }
}

// 页面过渡动画相关代码保持不变
class CustomPageTransitionBuilder extends PageTransitionsBuilder {
  @override
  Widget buildTransitions<T>(
      PageRoute<T> route,
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child,
      ) {
    return FadeTransition(
      opacity: animation,
      child: ScaleTransition(
        scale: animation,
        child: child,
      ),
    );
  }
}

class CustomPageTransitionBuilder2 extends PageTransitionsBuilder {
  @override
  Widget buildTransitions<T>(
      PageRoute<T> route,
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child,
      ) {
    final curvedAnimation = CurvedAnimation(
      parent: animation,
      curve: Curves.easeOutQuart,
      reverseCurve: Curves.easeInQuart,
    );

    return SlideTransition(
      position: Tween<Offset>(
        begin: const Offset(1, 0),
        end: Offset.zero,
      ).animate(curvedAnimation),
      child: FadeTransition(
        opacity: curvedAnimation,
        child: child,
      ),
    );
  }
}

class CustomPageTransitionBuilder3 extends PageTransitionsBuilder {
  @override
  Widget buildTransitions<T>(
      PageRoute<T> route,
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child,
      ) {
    final curvedAnimation = CurvedAnimation(
      parent: animation,
      curve: Curves.easeOutCubic,
      reverseCurve: Curves.easeInCubic,
    );

    return Center(
      child: FadeTransition(
        opacity: curvedAnimation,
        child: ScaleTransition(
          scale: Tween<double>(
            begin: 0.9,
            end: 1.0,
          ).animate(curvedAnimation),
          alignment: Alignment.center,
          child: child,
        ),
      ),
    );
  }
}

class CustomPageTransitionBuilderN extends PageTransitionsBuilder {
  @override
  Widget buildTransitions<T>(
      PageRoute<T> route,
      BuildContext context,
      Animation<double> animation,
      Animation<double> secondaryAnimation,
      Widget child,
      ) {
    return child;
  }
}
